package com.xing.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: xingfuhao
 * @Date: 2022/05/27/13:06
 */

@Slf4j
public final class HttpUtil {

    static final String POST = "POST";
    static final String GET = "GET";
    static final int CONN_TIMEOUT = 30000; //ms
    static final int READ_TIMEOUT = 30000; //ms


    /**
     * post方式发送http请求
     *
     * @param strUrl
     * @param reqData
     * @return
     */
    public static byte[] doPost(String strUrl, byte[] reqData) {
        return send(strUrl, POST, reqData);
    }


    /**
     * get方式发送http请求
     *
     * @param strUrl
     * @return
     */
    public static byte[] doGet(String strUrl) {
        return send(strUrl, GET, null);
    }

    public static byte[] send(String strUrl, String requestMethod, byte[] reqData) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();

            httpcon.setDoOutput(true);
            httpcon.setDoInput(true);

            httpcon.setUseCaches(false);
            httpcon.setInstanceFollowRedirects(true);
            httpcon.setReadTimeout(READ_TIMEOUT);
            httpcon.setConnectTimeout(CONN_TIMEOUT);

            httpcon.setRequestMethod(requestMethod);
            httpcon.connect();
            if (requestMethod.equalsIgnoreCase(POST)) {
                OutputStream os = httpcon.getOutputStream();
                os.write(reqData);
                os.flush();
                os.close();
            }
            InputStream inputStream = httpcon.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");


            BufferedReader in = new BufferedReader(inputStreamReader);
            String inputLine;
            StringBuilder bankXmlBuffer = new StringBuilder();
            while ((inputLine = in.readLine()) != null){
                bankXmlBuffer.append(inputLine);
            }
            in.close();
            httpcon.disconnect();
            return  bankXmlBuffer.toString().getBytes();

        } catch (Exception e) {
            log.error(e.toString(),e);
            e.printStackTrace();
            return null;
        }

    }


}
